import { createRouter, createWebHistory } from 'vue-router'
import { useTokenStore } from '@/stores/token'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
      meta: {
        title: '注册',
        requiresAuth: false
      }
    },
    {
      path: '/',
      component: () => import('@/views/LayoutView.vue'),
      redirect: '/books',
      meta: { requiresAuth: true },
      children: [
        {
          path: '/books',
          name: 'books',
          component: () => import('@/views/book/BookListView.vue'),
          meta: {
            title: '图书列表',
            requiresAuth: true
          }
        },
        {
          path: '/books/:id',
          name: 'bookDetail',
          component: () => import('@/views/book/BookDetailView.vue'),
          meta: {
            title: '图书详情',
            requiresAuth: true
          }
        },
        {
          path: '/borrows',
          name: 'borrows',
          component: () => import('@/views/borrow/BorrowListView.vue'),
          meta: {
            title: '借阅记录',
            requiresAuth: true
          }
        },
        {
          path: '/profile',
          name: 'profile',
          component: () => import('@/views/user/ProfileView.vue'),
          meta: {
            title: '个人信息',
            requiresAuth: true
          }
        },
        {
          path: '/password',
          name: 'password',
          component: () => import('@/views/user/PasswordView.vue'),
          meta: {
            title: '修改密码',
            requiresAuth: true
          }
        },
        {
          path: '/avatar',
          name: 'avatar',
          component: () => import('@/views/user/AvatarView.vue'),
          meta: {
            title: '修改头像',
            requiresAuth: true
          }
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/NotFoundView.vue'),
      meta: {
        title: '页面不存在'
      }
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `云图书馆 - ${to.meta.title}`
  }

  // 检查是否需要登录
  const tokenStore = useTokenStore()
  if (to.meta.requiresAuth && !tokenStore.token) {
    next({ name: 'login', query: { redirect: to.fullPath } })
  } else {
    next()
  }
})

export default router
